<template>
  <el-dialog
    v-loading="loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    :title="'补充' + title"
    :visible.sync="visible"
    :append-to-body="true"
    width="70%"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div>{{ title }}点击“添加”可以将图片添加至{{ title }}</div>
    <div class="d-flex flex-wrap text-center" style="max-height: 200px; overflow: auto; margin-top: 5px;">
      <template v-if="optionsList.length">
        <div v-for="item in optionsList" :key="item.fileId">
          <ImgItem :item="item">
            <el-button size="small" type="primary" @click="handleAdd(item)">添加</el-button>
          </ImgItem>
        </div>
      </template>
      <template v-else><div style="width: 100%" class="text-center">暂无数据</div></template>
    </div>
    <el-divider></el-divider>
    <div>{{ title }}点击“移除”可以移除选中的{{ title }}</div>
    <div class="d-flex flex-wrap" style="max-height: 200px; overflow: auto; margin-top: 5px;">
      <template v-if="currentList.length">
        <div v-for="item in currentList" :key="item.fileId">
          <ImgItem :item="item">
            <el-button style="" size="small" type="danger" @click="handleRemove(item)">移除</el-button>
          </ImgItem>
        </div>
      </template>
      <template v-else><div style="width: 100%" class="text-center">暂无数据</div></template>
    </div>
    <div slot="footer">
      <el-button @click="$emit('ontoggle', false)">取 消</el-button>
      <el-button type="primary" @click="handleSave">保 存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  completeHuXingPicture,
  getAllFrontAndbackVrData,
  getFrontAndbackVrData,
  getHouseInfo,
  vrcut,
  vrPicCut,
} from "@/api/user";
import { smoothAsyncHandler } from "@/utils/utilsNew";
import ImgItem from "@/views/components/ImgItem"


export default {
  components: {
    ImgItem,
  },
  props: {
    dialogUpdateImgVisible: {
      type: Boolean,
      default: false,
    },
    // 目前只有两种 户型图 or 室内图
    tagCode: {
      type: String,
      default: "",
    },
    houDelId: {
      type: String,
      default: "",
    },
    buildSize: {
      type: String | Boolean,
      default: "",
    },
  },
  data() {
    // 上边可选的图片的fileId列表
    this.immobileList = [];
    // 属于这个房源 但不属于本次操作主题的图片（如本次在补充室内图，则该值为其它的非室内图集合）
    this.otherList = [];
    // 已操作的缓存映射
    this.cacheObj = {};
    return {
      loading: false,
      visible: true,
      optionsList: [],
      currentList: [],
    };
  },
  created() {},
  async mounted() {
    this.loading = true;
    await smoothAsyncHandler(this.init());
    this.loading = false;
  },
  watch: {},
  computed: {
    title() {
      return this.tagCode == "huxingtu" ? "户型图" : "室内图";
    },
  },
  methods: {
    async init() {
      await this.initCurrentData();
      await this.initOptionsData();
    },

    async initOptionsData() {
      const param = { delId: this.houDelId };

      try {
        // 补充户型图
        if (this.tagCode == "huxingtu") {
          param.buildSize = this.buildSize;
          this.optionsList = await this.fetchOptionsList(completeHuXingPicture, param, (item, i) => {
            return {
              cover: "0",
              fileId: item.fileId.slice(item.fileId.lastIndexOf("/") + 1),
              houDelId: this.houDelId,
              id: "",
              tagCode: "huxingtu",
              tagName: "户型图",
              type: "pic",
              url: item.fileId,
            };
          });
        } else {
          // 补充室内图时
          this.optionsList = await this.fetchOptionsList(getFrontAndbackVrData, param, (item) => {
            return {
              cover: "0",
              fileId: item.thumburl, //接口变动——getFrontAndbackVrData不再返回fileId，直接使用thumburl字段来代替数据的唯一标志
              houDelId: this.houDelId,
              id: "",
              tagCode: "",
              tagName: "未选择",
              type: "pic",
              url: item.thumburl,
            };
          });
        }

        this.immobileList = this.optionsList.map((v) => v.fileId);
      } catch (error) {}
    },

    async fetchOptionsList(fetchApi, param, handler) {
      const { content = [], isSuccess } = await fetchApi(param);
      if (!isSuccess) {
        return Promise.reject();
      }
      return Promise.resolve(
        content
          .filter((v) => !!v)
          .map(handler)
          .filter((item) => {
            return !this.currentList.find((v) => item.fileId == v.fileId);
          }),
      );
    },

    async initCurrentData() {
      const { content } = await getHouseInfo({ houDelId: this.houDelId });
      this.currentList = content.houImageVO.filter((v) => {
        if (this.tagCode == "huxingtu") {
          return v.tagCode == "huxingtu";
        } else {
          return v.tagCode != "huxingtu" && v.tagCode != "xiaoqu";
        }
      });

      this.otherList = content.houImageVO.filter((item) => {
        return !this.currentList.find((v) => item.fileId == v.fileId);
      });
    },
    async handleAdd(item) {
      let i = this.optionsList.findIndex((v) => item.fileId == v.fileId);

      // 非户型图即室内图
      if (item.tagCode != "huxingtu") {
        this.loading = true;

        // const { content, isSuccess } = await vrcut({ fileId: item.fileId });
        const { content, isSuccess } = await vrPicCut({ url: item.fileId });
        this.loading = false;
        if (isSuccess && content && content.fileId) {
          let target = this.optionsList.splice(i, 1)[0];
          this.cacheObj[content.fileId] = target;

          this.currentList.push({
            cover: "0",
            fileId: content.fileId,
            houDelId: this.houDelId,
            id: "",
            tagCode: "",
            tagName: "未选择",
            type: "pic",
            url: content.url,
          });
        } else {
          this.$message.error("添加失败！");
        }

        // 户型图
      } else {
        let target = this.optionsList.splice(i, 1)[0];
        this.currentList.push(target);
      }
    },
    handleRemove(item) {
      let i = this.currentList.findIndex((v) => item.fileId == v.fileId);
      let target = this.currentList.splice(i, 1)[0];
      let cache = this.cacheObj[target.fileId];
      if (cache) {
        target = cache;
        delete this.cacheObj[target.fileId];
      }

      if (this.immobileList.includes(target.fileId)) {
        this.optionsList.push(target);
      }
    },
    handleSave() {
      this.$emit("onsaveimg", this.tagCode, this.currentList, this.otherList);
      this.$emit("ontoggle", false);
    },
  },
  beforeDestroy() {
    this.otherList = null;
    this.immobileList = null;
    this.cacheObj = null;
  },
};
</script>

<style scoped></style>
